package com.spring.demo.core.dao.hibernate;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.spring.demo.core.dao.HibernateBaseDao;

public abstract class AbstractHibernateDao<T> implements HibernateBaseDao<T> {

	protected Class<T> entityClass;

	@Autowired
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	public AbstractHibernateDao() {
		ParameterizedType genericSupperClass = (ParameterizedType) getClass()
				.getGenericSuperclass();
		entityClass = (Class<T>) genericSupperClass.getActualTypeArguments()[0];
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return getCurrentSession().createQuery(
				"from " + entityClass.getSimpleName()).list();
	}

	@Override
	public void delete(Long id) {
		T t = findOne(id);
		if (t != null) {
			getCurrentSession().delete(t);
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public T findOne(Long id) {
		return (T) getCurrentSession().get(entityClass, id);
	}

	@Override
	public void save(T t) {
		getCurrentSession().save(t);
	}

	@Override
	public T update(T t) {
		getCurrentSession().update(t);
		return t;
	}

	protected Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
}
